import React, { useEffect, useRef, useState } from "react";
import lessModule from "./index.module.less"
import { Button, DatePicker, Empty, message, Modal, Radio, RadioChangeEvent, Select, Space, Table, Upload } from "antd";
import Dragger from "antd/es/upload/Dragger";
import emptyImage from "../../../../assets/image/homePageReasoningPage-tableEmpty.png"
import featherImage from "../../../../assets/image/homePageMonitorPage-modalFeather.png"
import infoImage from "../../../../assets/image/homePageMonitorPage-modalInfo.png"
import { $labelDictInterface } from "../../../../common/type";
import { $Http } from "../../../../network";
import HomePage_ChartScatterComponent from "../../component/chartScatter";
import dayjs from "dayjs";

// 主页-滚动监测页面
const HomePage_MonitorPage = () => {
    // 单选框子项类型约束
    interface radioItemInterface {
        label: string
        dataLabel: string
        fileLabel: string
        fileAcceptList: Array<string>
    }
    // 页面dom
    const pageRef = useRef<HTMLDivElement>(null)
    // 源数据
    const [sourceData, setSourceData] = useState<object>({});
    // 监测日期
    const [monitorDate, setMonitorDate] = useState<string>("");
    // 表格表头列表
    const tableColumnList: Array<object> = [
        {
            title: '异常类型',
            dataIndex: "type",
            render: (text: string) => text ?? "-/-",
        },
        {
            title: '概率',
            dataIndex: "probability",
            width: 120,
            render: (text: string) => text ?? "-/-",
        },
    ]
    // 表格纵向滚动区域高度
    let [tableScrollH, setTableScrollH] = useState<number>(0)

    /**
     * @brief 监听时间选择框
     * @param 参数说明
     * @return 
     * @note 
     * @warning 
     */
    const change_datePicker = (_: any, dateStr: string) => {
        setMonitorDate(dateStr);
        $Http("rollMonitor", { monitorDate : dateStr }).then((res: any) => {
            setSourceData({ ...res })
        }).catch((err: any) => {
            setMonitorDate("");
            setSourceData({})
        })

    }

    /**
     * @brief 点击下载日志
     * @param 
     * @return 
     * @note 
     * @warning 
     */
    const click_downloadLog = () => {
        $Http("getLog", {}).then((res: any) => {
            const blob = new Blob(['\ufeff' + res], { type: 'text/csv;charset=utf-8;' });
            const url = URL.createObjectURL(blob);
            // 创建一个临时链接并点击下载
            const link = document.createElement('a');
            link.setAttribute('href', url);
            link.setAttribute('download', `日志.csv`);
            document.body.appendChild(link);
            link.click();

            // 清理
            document.body.removeChild(link);
            URL.revokeObjectURL(url);
            message.open({
                type: 'success',
                content: "下载成功！",
            })
        })
    }
    /**
     * @brief 表格
     * @param 参数说明
     * @return 返回值说明
     * @note 可选注意事项
     * @warning 可选警告信息
         */
    const className_tableRow = (record: object, idx: number) => {
        return sourceData["result"].split(",").includes(record['type']) ? `${lessModule["main-result__tableRow"]}` : ""
    }
    /**
     * @brief 获取表格纵向滚动区域高度
     * @param 
     * @return 
     * @note 
     * @warning 
    */
    const eventListener_windowResize = () => {
        if (pageRef.current) {
            // 页面高度 - 头部高度 - 主体上边距 - 表格表头高度  - 表格上下边框
            const bodyDom = document.querySelector('.ant-table-body') as HTMLElement
            tableScrollH = pageRef.current.clientHeight - 32 - 18 - 24 - 8 - 58.14 - 2
            setTableScrollH(tableScrollH)
            bodyDom.style.height = `${tableScrollH}px`
        }
    }





    useEffect(() => {
        eventListener_windowResize()
        // 表格纵向滚动区域高度监听器（监听浏览器页面的变化）
        window.addEventListener('resize', eventListener_windowResize);
        return () => {
            // 清除监听器
            window.removeEventListener('resize', eventListener_windowResize)
        };
    }, [])
    return (
        <div ref={pageRef} className={lessModule["homePageMonitorPage"]} >
            <header className={lessModule["homePageMonitorPage-header"]}>
                <DatePicker className={lessModule["reocrdModalComponentFormComponent-formItem__datePicker"]} value={monitorDate ? dayjs(monitorDate) : null} allowClear={false} onChange={change_datePicker} />
                <Button type="primary" onClick={click_downloadLog}>下载日志</Button>
            </header>
            <main className={lessModule["homePageMonitorPage-main"]}>
                <div className={lessModule["homePageMonitorPage-main__preview"]}>
                    <span>当前监测窗口曲线图（原始数据）</span>
                    {
                    Object.keys(sourceData).length > 0 && <HomePage_ChartScatterComponent sourceList={sourceData["value"]} />
                    }
                </div>
                <div className={lessModule["homePageMonitorPage-main__result"]}>
                    <div>监测结果：<span className={lessModule["main-result__value"]}>{sourceData["result"] ?? "N/A"}</span></div>
                    <Table rowKey={(record, idx) => "homePageMonitorPageTable" + idx} scroll={{ y: 2000 }} pagination={false} rowClassName={className_tableRow} columns={tableColumnList} dataSource={sourceData["details"]}
                        locale={{
                            emptyText: <Empty image={emptyImage} imageStyle={{
                                width: 120,
                                height: 120,
                                marginTop: (tableScrollH - 150) / 2,
                            }} />

                        }} />
                </div>
            </main>
        </div>
    )

}

export default HomePage_MonitorPage